<template>
    <div class="container-p">
        <!-- 第一步 -->
        <div class="pages" v-if="data.procedure == 'one'">
            <div class="header-h1">Step1 - {{ $t('webAuto.PublishInformation') }}</div>
            <div style="margin-bottom: 20px;">
                <el-input v-model="data.title" :placeholder="$t('webAuto.enterTitle')" />
            </div>
            <!-- 富文本编辑器 -->
            <div class="quillEditor">
                <toolbar style="border-bottom: 1px solid #dcdfe6;width: 100%;border-radius: 4px;" :editor="editorRef"
                    :default-config="toolbarConfig" mode="default" />
                <editor style="height: auto;min-height: 300px; overflow-y: hidden;" :default-config="editorConfig"
                    mode="default" @onCreated="onCreated" v-model="data.textDescription" />
            </div>
            <!-- 附件 -->
            <div class="set">
                <div class="set-button">
                    <el-upload v-model="data.fileList" class="upload-demo" :action="data.action" :headers="data.headers"
                        :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove"
                        :on-exceed="handleExceed">
                        <el-button class="add-button" type="primary">{{ $t('webAuto.AddAttachment') }}</el-button>
                    </el-upload>
                </div>
            </div>
            <div class="wrap-opt">
                <div>
                    <p v-if="data.save">{{ $t('webAuto.LastSaved') }} {{ data.times }}{{ $t('webAuto.minutesAgo') }}</p>
                </div>
                <div class="wrap-list">
                    <!-- <el-button type="danger" class="butt">删除</el-button> -->
                    <!-- <el-button class="butt">预览</el-button> -->
                    <el-button type="primary" class="butt" @click="nextClick">{{ $t('webAuto.nextStep') }}
                        <el-icon>
                            <ArrowRight />
                        </el-icon>
                    </el-button>
                </div>
            </div>
        </div>
        <!-- 第二步 -->
        <div class="pages" v-else>
            <div class="header-h1">Step2 - {{ $t('webAuto.publishSetting') }}</div>
            <div class="text-success" style="margin-bottom: 20px;color:#1ab394">{{ $t('webAuto.completeFollowing') }} </div>
            <div class="set-limits">
                <div class="set-header">
                    <div class="set-t">
                        <span>{{ $t('webAuto.RoleSetting') }}  - </span>
                        <span class="set-small">{{ $t('webAuto.canSeeIinformation') }}</span>
                    </div>
                    <div class="el-link--inner" @click="updateClicks">{{ $t('webAuto.ClickModify') }}</div>
                </div>
                <div class="set-body">{{ data.readingPermission }}</div>
                <div class="set-footer">{{ $t('webAuto.RoleRules') }}</div>
            </div>
            <div class="set-limits">
                <div class="set-header">
                    <div class="set-t">
                        <span> {{ $t('webAuto.OtherSettings') }} </span>
                    </div>
                </div>
                <div class="line">
                    <p class="label">{{ $t('webAuto.DisplayTitleOrNot') }}:</p>
                    <div class="content">
                        <el-checkbox v-model="data.checked" :label="$t('webAuto.titleRules')" size="large" />
                    </div>
                </div>
                <div class="line">
                    <p class="label">{{ $t('webAuto.PDFMainText') }}:</p>
                    <div class="content">
                        <el-checkbox v-model="data.checkedPDF" :label="$t('webAuto.PDFZhenwen')" size="large" />
                        <p style="color:#ed5565;font-size: 12px">{{ $t('webAuto.experimentalFeatures') }}</p>
                        <p style="color:#999;font-size: 12px"> {{ $t('webAuto.AfterSetting') }}</p>
                    </div>
                </div>
                <div class="line">
                    <p class="label">{{ $t('webAuto.MirrorSection') }}</p>
                    <div class="content">
                        <el-select v-model="data.mirrorColumn" :placeholder="$t('webAuto.selectMirrorColumn')">
                            <el-option v-for="item in data.mirrorList" :key="item.value" :label="item.title"
                                :value="item.uuid" />
                        </el-select>
                        <p class="small">{{ $t('webAuto.concurrence') }}</p>
                    </div>
                </div>
            </div>
            <div class="wrap-opt">
                <div>
                    <p v-if="data.save">{{ $t('webAuto.LastSaved') }} {{ data.times }}{{ $t('webAuto.minutesAgo') }}</p>
                </div>
                <div class="wrap-list">
                    <el-button class="butt" @click="data.procedure = 'one'"><el-icon>
                            <ArrowLeft />
                        </el-icon>{{ $t('webAuto.shangyibu') }}</el-button>
                    <el-button type="primary" class="butt" @click="saveClick" v-if="!data.confirm">{{ $t('webAuto.bangcun') }}</el-button>
                    <el-button type="primary" class="butt" @click="confirmReleaseClick" v-else>{{ $t('webAuto.ConfirmRelease') }}</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, shallowRef, onMounted } from "vue"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import "@wangeditor/editor/dist/css/style.css" // 引入 css
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from "vue-router";
import { useStore } from 'vuex';
import { useI18n } from 'vue-i18n';
import uuid from "@/utils/uuid.js";
import homePageApi from "@/api/homePage.js";
import homeApi from "@/api/home.js";
const { t } = useI18n();

const route = useRoute();
const router = useRouter();

const data = reactive({
    uuid: '',
    puuid: route.query.puuid,
    title: '',//标题
    content: '',
    textDescription: '',//富文本编辑器内容
    procedure: 'one',//步驟
    save: '', // 是否保存预览
    times: '', //保存时间
    fileList: [],
    checked: false,//是否显示标题
    checkedPDF: false,//  PDF作为正文
    mirrorColumn: '', // 镜像栏目
    mirrorList: [],//栏目list
    readingPermission: '爱丽家居科技股份有限公司[公司]',
    action: `http://${process.env.NODE_ENV === 'dev' ? '10.1.22.31:9991/wflow/oss/oss-simple?bizId=' : 'api.eletile.com:18081/wflow-api/wflow/oss/oss-simple?bizId='}`,//附件上传的地址
    // action: 'http://10.1.22.31:9991/wflow/oss/oss-simple?bizId=',
    isShow: '', // 是否显示标题
    isRelease: 'N',//是否发布
    type: '信息',
    confirm: false,
    headers: {
        wflowtoken: localStorage.getItem("wflow-token")
    },//文件上传
    filedPath: ''
})


onMounted(() => {
    if (route.query.uuid != 'null') {
        data.uuid = route.query.uuid
        column()
    } else {
        data.uuid = uuid()
    }
    data.action = data.action + data.uuid + '&bizType=wflow'
    homePageDetail()
})

// 获取内容详情 如果是存稿的点击进来
const column = () => {
    homeApi.readingLi(data.uuid).then(res => {
        console.log(res.data)
        data.title = res.data.title
        data.textDescription = res.data.textDescription
        data.checked = res.data.isShow == 'N' ? false : true
        data.mirrorColumn = res.data.mirrorColumn//镜像栏目
        data.filedPath = res.data.filePath
    }).catch(err => {
        console.log(err)
    })
}
//查询菜单信息
const homePageDetail = () => {
    homePageApi.getHomePage({
        pageSize: data.pageSize,
        pageNo: data.currentPage,
        type: '栏目',
    }).then(res => {
        data.mirrorList = res.data.records
    })
}

const serverUrl = ref(`http://${process.env.NODE_ENV === 'dev' ? '10.1.22.31:9991/wflow/oss/oss-simple?bizId=' : 'api.eletile.com:18081/wflow-api/wflow/oss/oss-simple?bizId='}` + uuid() + "&bizType=wflow&status=" + 0)
// 富文本实例对象
const editorRef = shallowRef()
// 菜单配置
const toolbarConfig = ref({})
// 编辑器配置
const editorConfig = ref({
    placeholder: "请输入内容...",
    readOnly: false, // 只读
    MENU_CONF: {
        // 配置上传图片
        uploadImage: {
            server: serverUrl.value, // 配置图片上传地址
            maxFileSize: 100 * 1024 * 1024, // 500M  图片大小限制
            fieldName: "file", // 上传名字
            allowedFileTypes: [], // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            // 自定义上传参数，传递图片时需要带一些参数过去写在这。参数会被添加到 formData 中，一起上传到服务端。
            // meta: {
            //   image_class_id: "2",
            //   file_type: "1",
            // },
            // 自定义设置请求头，比如添加token之类的
            headers: {
                // Accept: 'text/x-json',
                wflowtoken: localStorage.getItem("wflow-token")
            },
            // 上传进度的回调函数，可以用来显示进度条
            onProgress(progress) {
                // progress 是 0-100 的数字
                console.log("progress", progress)
            },
            // // 单个文件上传成功之后
            onSuccess(file, res) {
                console.log(`${file.name} 上传成功`, res)
            },

            // 单个文件上传失败
            onFailed(file, res) {
                console.log(`${file.name} 上传失败`, res)
            },

            // 上传错误，或者触发 timeout 超时
            onError(file, err, res) {
                console.log(`${file.name} 上传出错`, err, res)
            },

            // 插入图片到富文本编辑器回显
            customInsert(res, insertFn) {
                console.log(res)
                // res 即服务端的返回结果
                const url = res.data.url
                const alt = res.data.alt
                // 从 res 中找到 url alt href ，然后插入图片
                insertFn(url, alt)
            }
        }
    }
})

// 编辑器回调函数  工具栏
const onCreated = editor => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 页面最下面的  附件上传
// 点击文件列表中已上传的文件时的钩子
const handlePreview = (uploadFile) => {
    // console.log(uploadFile.response.data.url)
    window.open(uploadFile.response.data.url, '_blank')
}
// 文件列表移除文件时的钩子
const handleRemove = (file, uploadFiles) => {
    homeApi.deleteFile([file.response.data.uuid]).then(res => {
        console.log(res.data)
        if (res.data.statusCode == 200) {
            ElMessage.success({ message: res.data.message })

        }
    })
}
//删除文件之前的钩子，参数为上传的文件和文件列表，
//  若返回 false 或者返回 Promise 且被 reject，则停止删除。
const beforeRemove = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `Cancel the transfer of ${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}
//	当超出限制时，执行的钩子函数
const handleExceed = (files, uploadFiles) => {
    if (files.length > 100) {
        ElMessage.warning({ message: t('webAuto.attachmentsUploaded') })
    }
}

// 下一步
const nextClick = () => {
    console.log(data.uuid)
    if (!data.title) {
        ElMessage({
            message: t('webAuto.MissingTitle'),
            type: 'warning',
        })
        return
    }
    if (data.textDescription == '<p><br></p>') {
        ElMessage({
            message: t('webAuto.MissingMainText'),
            type: 'warning',
        })
        return
    }
    data.procedure = 'two'
    data.confirm = false
}

// 保存
const saveClick = () => {
    data.isShow = data.checked ? 'Y' : 'N'
    data.isPdf = data.checkedPDF ? 'Y' : 'N'
    homePageApi.addHomePage(data).then(res => {
        ElMessage.success( t('webAuto.baocunChenGong'))
        data.dialogVisible = false
        data.confirm = true
    }).catch(err => {
        ElMessage.error( t('webAuto.baocunShiBai'))
    })
}

// 发布
const confirmReleaseClick = () => {
    homePageApi.releaseData(data.uuid).then(res => {
        console.log(res.data)
        if (res.data.statusCode) {
            ElMessage.success(t('webAuto.fabuChenGong'))
            data.confirm = true
            // 判断是否pdf为正文
            if (data.isPdf == 'Y') {
                homeApi.readingLi(data.uuid).then(res => {
                    console.log(res.data)
                    data.filedPath = res.data.filePath
                    if (data.filedPath.length > 0) {
                        let previewUrl = 'http://180.101.147.124:8012/onlinePreview?url=' + encodeURIComponent(base64Encode(
                            `${data.filedPath}?name=${'文件预览'}`))
                        window.open(previewUrl,'_self')
                         router.replace('/')
                    }
                })

            } else {
                router.replace(`/read?uuid=${data.uuid}`)
            }
        }


    })
}
const base64Encode = (str) => {
    // console.log(str)
    // 将字符串转换为 Uint8Array
    const bytes = new TextEncoder().encode(str);
    // 使用 btoa() 方法进行 Base64 编码
    return btoa(String.fromCharCode.apply(null, bytes));
}


// 阅读权限修改
const updateClicks = () => {

}
</script>


<style scoped lang="less">
@import "index.less";

* {
    margin: 0;
    padding: 0;
}
</style>
